﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using SBACN.WebSite.Code;
using SBACN.WebSite.Models;

namespace SBACN.WebSite.Handler
{
	/// <summary>
	/// UploadHandler 的摘要说明
	/// </summary>
	public class UploadHandler : BaseHandler
	{
		public override void Process()
		{
			HttpContext context = base.httpContext;
			context.Response.Charset = "UTF-8";
			context.Response.ContentType = "text/plain";

			string busi_Dir = string.IsNullOrWhiteSpace(context.Request["tc"]) ? "/" : "/" + context.Request["tc"].Trim().ToLower() + "/";

			// 初始化一大堆变量
			string inputname = "filedata";			// 表单文件域name
			string attachdir = BasePage.UploadRootPath;		// 上传文件保存路径，结尾已经添加"/"
			int dirtype = 1;						// 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
			int maxattachsize = 1024 * 1024 * BasePage.MaxUploadSize;		// 最大上传大小
			string upext = BasePage.UploadFileTypes;			// 上传扩展名
			int msgtype = 2;						// 返回上传参数的格式：1，只返回url，2，返回参数数组
			string immediate = httpContext.Request.QueryString["immediate"];//立即上传模式，仅为演示用
			byte[] file;							// 统一转换为byte数组处理
			string localname = "";
			string disposition = httpContext.Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

			string err = "";
			string msg = "''";

			if (disposition != null)
			{
				// HTML5上传
				file = httpContext.Request.BinaryRead(httpContext.Request.TotalBytes);
				localname = httpContext.Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名
			}
			else
			{
				HttpFileCollection filecollection = httpContext.Request.Files;
				HttpPostedFile postedfile = filecollection.Get(inputname);

				// 读取原始文件名
				localname = postedfile.FileName;
				// 初始化byte长度.
				file = new Byte[postedfile.ContentLength];

				// 转换为byte类型
				System.IO.Stream stream = postedfile.InputStream;
				stream.Read(file, 0, postedfile.ContentLength);
				stream.Close();

				filecollection = null;
			}

			if (file.Length == 0)
			{
				err = "无数据提交";
			}
			else
			{
				if (file.Length > maxattachsize)
				{
					err = "文件大小超过" + BasePage.MaxUploadSize + "M!";
				}
				else
				{
					string attach_dir, attach_subdir, filename, extension, target;

					// 取上载文件后缀名
					extension = BasePage.GetFileExt(localname);
					if (("," + upext.ToLower() + ",").IndexOf("," + extension + ",") < 0)
					{
						err = "上传文件扩展名必需为：" + upext;
					}
					else
					{
						switch (dirtype)
						{
							case 2:
								attach_subdir = "month_" + DateTime.Now.ToString("yyyyMM");
								break;
							case 3:
								attach_subdir = "ext_" + extension;
								break;
							default:
								attach_subdir = "day_" + DateTime.Now.ToString("yyyyMMdd");
								break;
						}
						attach_dir = attachdir + attach_subdir + busi_Dir;

						// 生成随机文件名
						Random random = new Random();
						filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(99999).ToString("#00000") + "." + extension;

						target = attach_dir + filename;
						try
						{
							BasePage.CreateFolder(httpContext.Server.MapPath(attach_dir));

							System.IO.FileStream fs = new System.IO.FileStream(httpContext.Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
							fs.Write(file, 0, file.Length);
							fs.Flush();
							fs.Close();
						}
						catch (Exception ex)
						{
							err = ex.Message.ToString();
						}

						TB_UploadInfo uploadInfo = DAL.DALHelper.Instance.Create<TB_UploadInfo>();
						//uploadInfo.CreateBy = AdminInfo.UserName;
						uploadInfo.CreateDate = DateTime.Now;
						uploadInfo.FilePath = target;
						uploadInfo.FileType = BasePage.GetFileExt(extension);
						uploadInfo.Name = "编辑框上传文件";
						//uploadInfo.PrimaryID = news.ID;
						uploadInfo.Type = context.Request["tc"].Trim().ToLower();
						DAL.DALHelper.Instance.Add<TB_UploadInfo>(uploadInfo);
						DAL.DALHelper.Instance.SaveChanges();

						// 立即模式判断
						if (immediate == "1") target = "!" + target;
						target = jsonString(target);
						if (msgtype == 1) msg = "'" + target + "'";
						else msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
					}
				}
			}
			file = null;

			httpContext.Response.Write("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
		}

		string jsonString(string str)
		{
			str = str.Replace("\\", "\\\\");
			str = str.Replace("/", "\\/");
			str = str.Replace("'", "\\'");
			return str;
		}

	}
}